<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/15
 * Time: 20:44
 */

namespace app\sd\admin;

use app\admin\controller\Admin;
use app\sd\model\WeUsers as WeUserModel;
use app\api\model\WeUsers as ApiUserModel;
use app\common\builder\ZBuilder;
use think\Db;
use think\Exception;

class WeUsers extends Admin
{
    public function index()
    {
        $map = $this->getMap() ? $this->getMap() : [];
        $order = $this->getOrder() ? $this->getOrder() : 'create_time desc';
        $data_list = WeUserModel::userList($map, $order);
        $fields = [
            ['text', 'nick_name', '昵称'],
            ['select', 'gender', '性别', '', [1 => '男', '2' => '女', '0' => '未知']],
            ['hidden', 'type', '2'],
        ];
        $columns = [
            ['id', 'ID'],
            ['nick_name', '微信昵称'],
            ['we_nick_name', '微信小程序昵称'],
            ['reset_name','重置昵称'],
            ['avatar_url', '头像', 'img_url'],
            ['status', '状态', 'switch'],
            ['right_button', '操作', 'btn']
        ];
        return ZBuilder::make('table')
            ->autoAdd($fields, 'we_users')
            ->addTopSelect('gender', '性别', [1 => '男', '2' => '女', '0' => '未知'])
            ->addTopSelect('type', '用户分组', [1 => '微信用户', '2' => '自定义用户', '0' => '未知'])
            ->setSearch(['nick_name' => '昵称', 'id' => 'ID'])
            ->addColumns($columns)
            ->addRightButtons(['delete', 'reset_name' => [
                'href' => 'resetNickName?id=__id__',
                'title' => '重置昵称',
                'icon' => 'fa fa-cogs'
            ]])
            ->setTableName('we_users')
            ->setRowList($data_list)
            ->fetch();
    }


    /**
     * @throws \think\exception\DbException
     */
    public function resetNickName()
    {
        $id = $this->request->get('id');
        $userInfo = WeUserModel::get($id);
        if (empty($userInfo)) {
            return $this->error('未查询到用户', 'index');
        } else {
            $weUsers = new ApiUserModel();
            $userInfo->we_nick_name = $weUsers->genWeNickName();
            Db::startTrans();
            try {
                $res = $userInfo->save();
                if (!$res) {
                    throw new Exception('重置昵称失败');
                }
            } catch (Exception $exception) {
                Db::rollback();
                return $this->error($exception->getMessage(), 'index');
            }
            Db::commit();
            return $this->success('重置昵称成功', 'index');
        }
    }
}